package com.emmmya.ocs.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.emmmya.ocs.common.entity.IntermediateEntity;
import com.emmmya.ocs.common.entity.LayUIXmSelect;
import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.vo.Result;
import com.emmmya.ocs.modules.system.annotation.OperateLog;
import com.emmmya.ocs.modules.system.entity.Role;
import com.emmmya.ocs.modules.system.entity.User;
import com.emmmya.ocs.modules.system.service.RoleService;
import com.emmmya.ocs.modules.system.service.UserService;
import com.emmmya.ocs.modules.system.utils.LayuiTreeUtils;
import com.emmmya.ocs.modules.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2021-01-28
 * @version: 1.0
 */
@RequestMapping("role")
@Controller
// 角色管理器
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;


    @Autowired
    LayuiTreeUtils layuiTreeUtils;

    /**
     * 根据id查询role信息
     */
    @PostMapping(value="getRoleById")
    @ResponseBody
    //@OperateLog(value="根据id查询角色",module = "角色管理",operateType=0)
    //@ApiOperation(value="根据id查询角色",response=Result.class, code=200,httpMethod = "POST")
    //@ApiImplicitParams(@ApiImplicitParam(name="id",value="角色ID",dataType = "String",paramType = "query"))
    public Result<Object> getRoleById(String id){
        Role role = roleService.get(Long.parseLong(id));
        if(role == null){
            return ResultUtil.error("未查到该用户信息");
        }
        return ResultUtil.data(role);
    }

    /**
     * 根据id删除role
     * 删除前，应该解绑role与 user 的关系 、也应该解绑 role 和 permission
     */
    @RequestMapping(value="deleteRoleById",method= RequestMethod.DELETE)
    @ResponseBody
    @OperateLog(value="根据id删除角色",module = "角色管理",operateType=4)
    public Result<Object> deleteRoleById(String id){
        roleService.delete(Long.parseLong(id));
        return ResultUtil.success("删除成功！");
    }


    /**
     *  role对象里面有不同的对象嵌套 传参时候，必须使用@RequestBody,不然启动会报错，虽然不影响
     * @param vo
     * @return
     */
    @GetMapping("getRoleList")
    @ResponseBody
    //@OperateLog(value="获取角色列表",module = "角色管理",operateType=0)
    public Result<Object> getRoleList(RoleVo vo){
        IPage<Role> page = roleService.getListByPage(vo);
        return ResultUtil.data(page,"成功");
    }

    @GetMapping("getRolesByUserId")
    @ResponseBody
    //@OperateLog(value="根据用户id获取角色",module = "角色管理",operateType=0)
    public Result<Object> getRolesByUserId(@RequestParam("userId")Long userId){
        User user = userService.get(userId);
        if(user == null){
            return ResultUtil.error("用户不存在！");
        }
        List<Role> userRoles = user.getRoles();

        List<Role> allRoles = roleService.getAll();

        //转换成xm-select多选框的模式
        List<LayUIXmSelect> layUIXmSelects = layuiTreeUtils.changeSelecte(allRoles, userRoles);


        //layuiTreeUtils.changeTree()
        return ResultUtil.data(layUIXmSelects);


    }

    @RequestMapping("addOrUpdateRole")
    @ResponseBody
    @OperateLog(value="新增或修改角色",module = "角色管理",operateType=23)
    public Result<Object> addOrUpdateRole(@RequestBody Role role){
        String content = "";
        try {
            if(role.getId()==null || role.getId() == 0L) {
                roleService.save(role);
                content = "新增";

            }else{
                roleService.update(role);
                content = "更新";
            }
            return ResultUtil.success(content+"成功!");
        } catch (Exception e) {
            //e.printStackTrace();
            return ResultUtil.success(content+"操作失败!请联系管理处理。错误信息："+e.getMessage());
        }
    }

    @RequestMapping("updateRoleMenu")
    @ResponseBody
    @OperateLog(value="修改角色绑定的菜单",module = "角色管理",operateType=3)
    public Result<Object> updateRoleMenu(@RequestParam(value="roleId") Long roleId,
                                         @RequestParam(value="checkedMenu[]")Integer[] checkedMenu){
        List<IntermediateEntity> roleMenus = new ArrayList<>();
        List<Integer> cheackMenuIdList = Arrays.stream(checkedMenu).collect(Collectors.toList());
        try {
            //先删除原先的数据。
            int i = roleService.deleteRoleMenuByRoleId(roleId);
            //再插入新数据
            for (Integer menuId : cheackMenuIdList) {
                IntermediateEntity data = new IntermediateEntity(roleId,menuId.longValue());
                roleMenus.add(data);
            }
            if(!roleMenus.isEmpty()){
                roleService.insertRoleMenus(roleMenus);
            }
            return ResultUtil.success("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("修改失败！错误信息:"+e.getMessage());
        }
    }

    @RequestMapping("updateRolePermission")
    @ResponseBody
    @OperateLog(value="修改角色绑定的权限",module = "角色管理",operateType=3)
    public Result<Object> updateRolePermission(@RequestParam(value="roleId") Long roleId,@RequestParam(value="checkedPermissions[]")Long[] checkedPermissions){
        List<IntermediateEntity> roleMenus = new ArrayList<>();
        List<Long> checkedPermissionIdList = Arrays.stream(checkedPermissions).collect(Collectors.toList());
        try {
            //先删除原先的数据。
            int i = roleService.deleteRoleMenuByRoleId(roleId);
            //再插入新数据
            for (Long permission : checkedPermissionIdList) {

                IntermediateEntity data = new IntermediateEntity(roleId,permission);
                roleMenus.add(data);

            }
            if(!roleMenus.isEmpty()){

                roleService.insertRoleMenus(roleMenus);

            }
            return ResultUtil.success("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("修改失败！错误信息:"+e.getMessage());
        }
    }

    @RequestMapping("changeDefaultRole")
    @ResponseBody
    @OperateLog(value="修改默认角色",module = "角色管理",operateType=3)
    public Result<Object> changeDefaultRole(@RequestParam("roleId")Long roleId){
        try {
            //先拿到之前默认角色并把其默认标识设置为false
            List<Role> defaultRoles = roleService.findRolesByDefaultRole(true);
            if(!defaultRoles.isEmpty()){
                defaultRoles.forEach(e->{
                    e.setDefaultRole(false);
                });
                roleService.saveOrUpdateAll(defaultRoles);
            }
            //查询传来值过来的id，得到Role。更新默认标识
            Role role = roleService.get(roleId);
            role.setDefaultRole(true);
            roleService.update(role);
            return ResultUtil.success("默认角色成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("默认角色失败!错误信息:"+e.getMessage());
        }
    }
}